package ren.xbcr.schoolbus.client;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.SeekBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import ren.xbcr.schoolbus.client.domain.LoginUser;
import ren.xbcr.schoolbus.client.domain.RecruitDriver;
import ren.xbcr.schoolbus.client.domain.ValidationMark;
import ren.xbcr.schoolbus.client.domain.transmission.ResponseResult;
import ren.xbcr.schoolbus.client.domain.transmission.ResponseResultWithRecruitDriver;
import ren.xbcr.schoolbus.client.service.SchoolBusService;
import ren.xbcr.schoolbus.client.util.PrefUtils;
import ren.xbcr.schoolbus.client.util.SchoolArrayAdapter;
import ren.xbcr.schoolbus.client.util.Tool;

public class RecruitDriverActivity extends AppCompatActivity {

    private EditText mTeleNumEditor;
    private AutoCompleteTextView mSchoolEditor;
    private TextView mWorkHourLabel;
    private SeekBar mWorkHourSeeker;
    private EditText mPhoneValidCodeEditor;
    private EditText mDescriptionEditor;
    private View mRecruitFormView;
    private View mProgressView;

    private ViewGroup mSmsCodeLayout;
    private String mTelephone;
    private String mSchool;
    private Button mRecruitButton;
    private Set<String> mSchools;
    private RecruitDriverTask mRecruitDriverTask = null;
    private FetchExistRecruitTask mFetchExistRecruitTask = null;

    private Button mCallCarButton;
    private Button mDriverRatingButton;
    private Button mAboutBusinessButton;
    private Button mRecruitDriverButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recruit_driver);

        new SchoolArrayTask(getApplicationContext()).execute((Void) null);

        mTelephone = PrefUtils.getStringFromPrefs(getApplicationContext(), PrefUtils.PREFS_LOGIN_TELEPHONE, null);
        mSchool = PrefUtils.getStringFromPrefs(getApplicationContext(), PrefUtils.PREFS_LOGIN_SCHOOL, null);
        mSchoolEditor = (AutoCompleteTextView) findViewById(R.id.recruit_school);
//        mSchools = PrefUtils.getStringSetFromPrefs(getApplicationContext(), PrefUtils.PREFS_SCHOOL_NAME, null);
        if (mTelephone != null && !mTelephone.isEmpty()) {
            mTeleNumEditor = (EditText) findViewById(R.id.phone_number);
            mTeleNumEditor.setText(mTelephone);
            mSchoolEditor.setText(mSchool);

            mFetchExistRecruitTask = new FetchExistRecruitTask(this, mTelephone);
            mFetchExistRecruitTask.execute((Void) null);

        } else {
            setResult(RESULT_CANCELED);
            finish();
        }
        mRecruitFormView = findViewById(R.id.recruit_form);
        mProgressView = findViewById(R.id.recruit_progress);
        mSmsCodeLayout = (ViewGroup) findViewById(R.id.sms_verify_form);
        setupHourSeeker();
        mPhoneValidCodeEditor = (EditText) findViewById(R.id.sms_verify_code);
        mDescriptionEditor = (EditText) findViewById(R.id.recruit_description);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        mTeleNumEditor.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (mTelephone.equals(s.toString())) {
                    mSmsCodeLayout.setVisibility(View.GONE);
                } else {
                    mSmsCodeLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mRecruitButton = (Button) findViewById(R.id.recruit_apply);
        mRecruitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                attemptLogin();
                driverRecruit();
            }
        });

        setupBtn();
//
//        ActionBar actionBar = getSupportActionBar();
//        actionBar.setDisplayHomeAsUpEnabled(true);

        // show for fetch exist recruit
        showProgress(true);


    }

    private void setupHourSeeker() {

        mWorkHourLabel = (TextView) findViewById(R.id.work_hour_label);
        mWorkHourSeeker = (SeekBar) findViewById(R.id.work_hour_num_picker);
        mWorkHourSeeker.incrementProgressBy(1);
        mWorkHourLabel.setText(String.format(getString(R.string.prompt_recruit_work_hour), mWorkHourSeeker.getProgress() / 2.0));

        mWorkHourSeeker.requestFocus();

        mWorkHourSeeker.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                if (progress < 1) {
                    progress = 1;
                    seekBar.setProgress(1);
                }
                double hour = progress / 2.0;
//                progress = progress * 10;
                mWorkHourLabel.setText(String.format(getString(R.string.prompt_recruit_work_hour), hour));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        /*mWorkHourSeeker.setMinValue(1);
        mWorkHourSeeker.setMaxValue(24);*/
    }


    private void setupBtn() {
        final FragmentActivity activity = this;
        mCallCarButton = (Button) findViewById(R.id.main_map_button);
        mCallCarButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Tool.navToLoginActivity(RecruitDriverActivity.this, activity)) return;
                Intent intent = new Intent(RecruitDriverActivity.this, MainActivity.class);
                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(intent);
            }
        });

        mDriverRatingButton = (Button) findViewById(R.id.driver_rating_btn);
        mDriverRatingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Tool.navToLoginActivity(RecruitDriverActivity.this, activity)) return;
                Intent intent = new Intent(RecruitDriverActivity.this, DriverListActivity.class);
                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(intent);
            }
        });

        mAboutBusinessButton = (Button) findViewById(R.id.about_business_btn);
        mAboutBusinessButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Tool.navToLoginActivity(RecruitDriverActivity.this, activity)) return;
                Intent intent = new Intent(RecruitDriverActivity.this, BusinessCooperationActivity.class);
                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(intent);
            }
        });

        mRecruitDriverButton = (Button) findViewById(R.id.recruit_driver_btn);
        mRecruitDriverButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               /* if (Tool.navToLoginActivity(RecruitDriverActivity.this, activity)) return;
                Intent intent = new Intent(RecruitDriverActivity.this, RecruitDriverActivity.class);
                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(intent);*/
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; goto parent activity.
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void driverRecruit() {
        String school = mSchoolEditor.getText().toString();
        String phoneValidCode = mPhoneValidCodeEditor.getText().toString();

        ValidationMark validationMark = new ValidationMark();
        validationMark.setCancel(false);

        if (!validationMark.getCancel() && (school == null || school.isEmpty())) {
            mSchoolEditor.setError(getString(R.string.error_school_empty));
            validationMark.setFocusView(mSchoolEditor);
            validationMark.setCancel(true);
        }
//        String[] schoolList = getResources().getStringArray(R.array.schools_array);
        if (!validationMark.getCancel() && !mSchools.contains(school)) {
            mSchoolEditor.setError(getString(R.string.error_school_not_contains));
            validationMark.setFocusView(mSchoolEditor);
            validationMark.setCancel(true);
        }
/*        String telephone = Tool.verifyTelephone(getApplicationContext(), validationMark, mTeleNumEditor);
        if (!validationMark.getCancel() && (phoneValidCode == null || phoneValidCode.isEmpty())) {
            mPhoneValidCodeEditor.setError(getString(R.string.error_sms_valid_code_empty));
            validationMark.setFocusView(mPhoneValidCodeEditor);
            validationMark.setCancel(true);
        }
        if (!validationMark.getCancel() && (phoneValidCode.length() != 4)) {
            mPhoneValidCodeEditor.setError(getString(R.string.error_sms_valid_code_format));
            validationMark.setFocusView(mPhoneValidCodeEditor);
            validationMark.setCancel(true);
        }*/


        if (validationMark.getCancel()) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            validationMark.getFocusView().requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            LoginUser loginUser = new LoginUser(mSchool, null, mTelephone);
            RecruitDriver recruitDriver = new RecruitDriver(mDescriptionEditor.getText().toString(),
                    loginUser, school, phoneValidCode, mTelephone,
                    mWorkHourSeeker.getProgress()/2.0);
            mRecruitDriverTask = new RecruitDriverTask(this, recruitDriver);
            mRecruitDriverTask.execute((Void) null);
        }
    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mRecruitFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mRecruitFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mRecruitFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mRecruitFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }


    public class RecruitDriverTask extends AsyncTask<Void, Void, Boolean> {

        private final Context mContext;
        private final RecruitDriver mRecruitDriver;

        RecruitDriverTask(Context context, RecruitDriver recruitDriver) {
            mContext = context;
            mRecruitDriver = recruitDriver;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            Boolean isSuccess = false;
            SchoolBusService schoolBusService = new SchoolBusService();
            isSuccess = schoolBusService.recruitDriver(mRecruitDriver);

            return isSuccess;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mRecruitDriverTask = null;
//            showProgress(false);

            if (success) {

                showProgress(false);
                Tool.showToast(mContext, mContext.getString(R.string.success_recruit_driver));
                mRecruitButton.setEnabled(false);
            } else {
                showProgress(false);
                mPhoneValidCodeEditor.setError(getString(R.string.error_recruit_driver));
                mPhoneValidCodeEditor.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mRecruitDriverTask = null;
            showProgress(false);
        }
    }


    public class FetchExistRecruitTask extends AsyncTask<Void, Void, ResponseResultWithRecruitDriver> {

        private final Context mContext;
        private final String mTelephoneNumber;

        FetchExistRecruitTask(Context context, String telephoneNumber) {
            mContext = context;
            mTelephoneNumber = telephoneNumber;
        }

        @Override
        protected ResponseResultWithRecruitDriver doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            ResponseResultWithRecruitDriver result = null;
            LoginUser loginUser = new LoginUser();
            loginUser.setTelephoneNumber(mTelephoneNumber)
            ;
            SchoolBusService schoolBusService = new SchoolBusService();
            result = schoolBusService.fetchExistRecruit(loginUser);

            return result;
        }

        @Override
        protected void onPostExecute(final ResponseResultWithRecruitDriver result) {
            mFetchExistRecruitTask = null;
//            showProgress(false);

            if (result != null && result.getResultCode() == ResponseResult.RESULT_SUCCESS
                    && result.getResult() != null) {

                RecruitDriver recruitDriver = result.getResult();
                showProgress(false);
                mTeleNumEditor.setText(recruitDriver.getTelephone());
                mSchoolEditor.setText(recruitDriver.getSchoolName());

                Double process = recruitDriver.getWorkHour() * 2;
                mWorkHourSeeker.setProgress(process.intValue());
                mWorkHourLabel.setText(String.format(getString(R.string.prompt_recruit_work_hour),recruitDriver.getWorkHour()));

                mDescriptionEditor.setText(recruitDriver.getDescription());


            } else {
                showProgress(false);
                mPhoneValidCodeEditor.setError(getString(R.string.error_recruit_driver));
                mPhoneValidCodeEditor.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mFetchExistRecruitTask = null;
            showProgress(false);
        }
    }

    private class SchoolArrayTask extends AsyncTask<Void, Void, ArrayList<String>> {
        private Context mContext;

        public SchoolArrayTask(Context context) {

            mContext = context;
        }

        @Override
        protected ArrayList<String> doInBackground(Void... params) {
            try {
                SchoolBusService schoolBusService = new SchoolBusService();
                ArrayList<String> schools = schoolBusService.getAllSchool();
                return schools;
            } catch (Exception e) {
                Log.e("MainActivity", e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(ArrayList<String> schools) {
// Create the adapter and set it to the AutoCompleteTextView
            mSchools = new HashSet<String>(schools);
            SchoolArrayAdapter adapter =
                    new SchoolArrayAdapter(mContext, android.R.layout.simple_list_item_1, schools);
            mSchoolEditor.setAdapter(adapter);
        }
    }
}
